//
//  NetConnection.m
//  weizhuan
//
//  Created by lixun on 13-8-2.
//  Copyright (c) 2013年 lixun. All rights reserved.
//

#import "NetUtility.h"
#import "AppUtility.h"
#import "NetHttp.h"
#import "JSONParser.h"
#import "MBProgressHUD.h"
#import "ASIFormDataRequest.h"
#import "NSString+SBJSON.h"
#import "NSString+Alert.h"
#import "Reachability.h"
#import <netdb.h>
#include <sys/socket.h>
#include <sys/sysctl.h> 
#include <net/if.h> 
#include <net/if_dl.h>
#import "AppDelegate.h"
#include "AccountController.h"
#import "NSString+MD5Addition.h"
#import "IPAdress.h"
#import "LoadingView.h"

extern NSString *CTSettingCopyMyPhoneNumber();

@implementation NetUtility


+(NSString *)getsoftware
{
    NSString *ss= @"";
    ss =[[UIDevice currentDevice] systemVersion];
    return ss;

}




+(NSString *)getFenBianLv
{
    CGRect rect = [[UIScreen mainScreen] bounds];
    
    CGSize size = rect.size;
    
    CGFloat width = size.width;
    
    CGFloat height = size.height;
    
    //分辨率
    
    CGFloat scale_screen = [UIScreen mainScreen].scale;
    
    NSString *str =[NSString stringWithFormat:@"%dx%d",(int)width*(int)scale_screen,(int)height*(int)scale_screen];
    return str;
}

+(NSString *)getNetType //获取设备联网方式
{
    Reachability *r =[Reachability  reachabilityWithHostName:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            // 没有网络连接
            return @"没有网络连接";
            break;
        case ReachableViaWWAN:
            // 使用3G网络
            return @"使用3G网络";
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络
            return @"使用WiFi网络";
            break;
    }
    return Nil;
}

+ (BOOL)isConnected{
	return [NetHttp isConnected];
}

+ (NSMutableDictionary*)addHudDictInView:(UIView*)inView andStr:(NSString*)inStr {
	NSMutableDictionary* hudDict=[[NSMutableDictionary alloc] initWithCapacity:1];
	MBProgressHUD *progressHud = [[MBProgressHUD alloc] initWithView:inView];
	[progressHud setBackgroundColor:[UIColor colorWithRed:233/255.0 green:233/255.0 blue:233/255.0 alpha:0.3]];
	[progressHud setLabelText:inStr];
	[hudDict setObject:progressHud forKey:@"MBProgressHUD"];
	[hudDict setObject:inView forKey:@"HudRootView"];
	[progressHud release];
	return hudDict;
}

+ (void)displayHudDict:(NSMutableDictionary*)inHudDict{
	MBProgressHUD* progressHud=[inHudDict objectForKey:@"MBProgressHUD"];
	UIView* rootView=[inHudDict objectForKey:@"HudRootView"];
	[rootView addSubview:progressHud];
	[AppUtility showNetworkActivityIndicator:YES];
	[progressHud show:YES];
}

+ (void)releaseHudDict:(NSMutableDictionary*)inHudDict{
	MBProgressHUD* progressHud=[inHudDict objectForKey:@"MBProgressHUD"];
	[progressHud hide:YES];
	if(inHudDict) { 
		[inHudDict release]; 
	}
	if (progressHud) {
		[progressHud removeFromSuperview];
	}
	[AppUtility showNetworkActivityIndicator:NO];
} 

//用于异步Post
+ (id)getDataWithURLStr:(NSString*)inURLString andPostStr:(NSString*)inPostStr {
    
longinOver:
	if (![self isConnected]) {
        NSString *message = @"请检查您的网络或稍后重试";

        [message showAlert];
	}
//    [AppUtility showNetworkActivityIndicator:YES];
	NetHttp *httpRequest = [[NetHttp alloc] init];
	NSData *data =  [httpRequest sendPostRequestWithURLStr:inURLString andPostStr:inPostStr];
	[httpRequest release];
    
//    [AppUtility showNetworkActivityIndicator:NO];
	if (!data) {
		return nil;
	}
    NSDictionary *tmpDict = [JSONParser parserData:data isAllValues:YES valueForKey:nil];
    
    if (tmpDict && [tmpDict isKindOfClass:[NSDictionary class]])
    {
        if ([tmpDict objectForKey:@"code"])
        {
            
            
            int status =[[tmpDict objectForKey:@"code"] intValue];
            
//            if (status==0)
//            {
//                NSString *title = @"温馨提示";
//                NSString *message = [tmpDict objectForKey:@"i"] ;
//                UIImage *image = [AppUtility getLocalImage:@"icon_face_warning"];
//                
//                AHAlertView *alert = [[AHAlertView alloc] initWithTitle:title message:message icon:image];
//                [alert show];
//                
//                [alert setCancelButtonTitle:@"确认" block:^{
//                    
//
//                }];
//                [alert release];
//                return tmpDict;
//            }
            
            
            if (status==404)
                
            {
                NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:KUDAppTDWNO];
                
                NSString *passStr = [[NSUserDefaults standardUserDefaults] objectForKey:KUDAppTDWPass];
                
                if (![name isEqualToString:@""]&&name!=passStr) {
                    
                    NSString *postStr = [NSString stringWithFormat:@"username=%@&password=%@",name, passStr];
                    NSDictionary *resultDict =[NetUtility getDataWithURLStr:[NSString stringWithFormat:@"%@",KURLLogin] andPostStr:postStr];
                    UEXNSLog(@" -------%@%@  resultDict = %@",KURLLogin,postStr,resultDict);
                    if (resultDict) {
                        int stauts = [[resultDict objectForKey:@"s"] intValue];
                        
                        if (stauts==1) {
                            
                            
                            [AccountController setAccountState:kAccountStateLogin];
                            [AccountController setAccountInfo:[resultDict objectForKey:@"d"]];
                            goto longinOver;
                            
                            
                            
                        }
                    }
                    
                    
                    
                }
            }
            
            
            
        }
    }
	return tmpDict;
}

//用于异步Post，模拟Form表单
+ (id)getDataWithURLStr:(NSString*)inURLString andPostDict:(NSDictionary*)inPostDict {
    if (![self isConnected]) {
		UIAlertView* alertView= [[UIAlertView alloc] initWithTitle:@"网络错误"
														   message:@"请检查您的网络或稍后重试"
														  delegate:nil
												 cancelButtonTitle:@"确定"
												 otherButtonTitles:nil];
		[alertView show];
		[alertView release];
		return nil;
	}
	[AppUtility showNetworkActivityIndicator:YES];
	ASIFormDataRequest *asiFormRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:inURLString]];
	if ([inPostDict isKindOfClass:[NSDictionary class]] && [inPostDict count] != 0) {
        for (NSString *key in [inPostDict allKeys]) {

            [asiFormRequest setPostValue:[inPostDict objectForKey:key] forKey: key];
        }
	}
    [asiFormRequest setPostValue:@"1" forKey: @"ajax"];
    [asiFormRequest buildRequestHeaders];
    [asiFormRequest startSynchronous];
   	[AppUtility showNetworkActivityIndicator:NO];
	return [[asiFormRequest responseString] JSONValue];
}

//用于同步Post，模拟Form表单
+ (id)getDataWithURLStr:(NSString*)inURLString andPostDict:(NSDictionary*)inPostDict andView:inView{
    if (![self isConnected]) {
		UIAlertView* alertView= [[UIAlertView alloc] initWithTitle:@"网络错误"
														   message:@"请检查您的网络或稍后重试"
														  delegate:nil
												 cancelButtonTitle:@"确定"
												 otherButtonTitles:nil];
		[alertView show];
		[alertView release];
		return nil;
	}
	[AppUtility showNetworkActivityIndicator:YES];
	NSMutableDictionary *hudDict = [self addHudDictInView:inView andStr:@"  请稍候...  "];
	[self displayHudDict:hudDict];
	ASIFormDataRequest *asiFormRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:inURLString]];
	if ([inPostDict isKindOfClass:[NSDictionary class]] && [inPostDict count] != 0) {
        for (NSString *key in [inPostDict allKeys]) {

            [asiFormRequest setPostValue:[inPostDict objectForKey:key] forKey: key];
        }
	}
    [asiFormRequest setPostValue:@"1" forKey: @"ajax"];
    [asiFormRequest buildRequestHeaders];
    [asiFormRequest startSynchronous];

    [self releaseHudDict:hudDict];
	[AppUtility showNetworkActivityIndicator:NO];
	return [[asiFormRequest responseString] JSONValue];
}


+ (id)getDataWithURLStr:(NSString*)inURLString andPostStr:(NSMutableDictionary*)inPostDic andType:(NSString*)inType andImageDict:(NSMutableDictionary *)imageDic{
    
    
    ASIFormDataRequest *asiFormRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:inURLString]];
    
    NSArray *keyArray = [inPostDic allKeys];
    
    for (NSString *key in keyArray) {
        
        [asiFormRequest setPostValue:[inPostDic objectForKey:key] forKey:key];
        
        UEXNSLog(@"key --------------= %@---------->%@",key,[inPostDic objectForKey:key]);
        
    }
    
    NSString *fileName = @"";
    fileName = [NSString stringWithFormat:@"%d.jpg",[AppUtility getRand]];
    
    
    NSArray *keykeyArray = [imageDic allKeys];

    
    for (NSString *key in keykeyArray) {

    
        NSMutableArray *aary = [imageDic objectForKey:key];
    
        for (int i = 0; i<aary.count; i++) {
        
            [asiFormRequest addData:UIImageJPEGRepresentation([aary objectAtIndex:i],0.5) withFileName:fileName andContentType:@"image/jpeg" forKey:[NSString stringWithFormat:@"%@_%d",key,i]];
            
        }
        
    }
    
    [asiFormRequest setTimeOutSeconds:20];
    [asiFormRequest setDelegate:self];
    
    [asiFormRequest buildRequestHeaders];
    [asiFormRequest startSynchronous];
    
    UEXNSLog(@"1111111111-----%@",[asiFormRequest responseString]);
    return [[asiFormRequest responseString] JSONValue];


}


//显示请稍后 上传图片等
+ (id)getDataWithURLStr:(NSString*)inURLString andPostStr:(NSMutableDictionary*)inPostDic andType:(NSString*)inType andImageArray:(NSMutableArray *)imageArray andDataKey:(NSString*)inDataKey {
    
    
    ASIFormDataRequest *asiFormRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:inURLString]];
    
    
    
    NSArray *keyArray = [inPostDic allKeys];
    
    for (NSString *key in keyArray) {
        
        [asiFormRequest setPostValue:[inPostDic objectForKey:key] forKey:key];
        
        UEXNSLog(@"key --------------= %@---------->%@",key,[inPostDic objectForKey:key]);

    }

    
//    if ([inPostStr isKindOfClass:[NSString class]] && inPostStr.length != 0) {
////        [asiFormRequest setPostValue:inPostStr forKey: @"postData"];
//    }
//    
    
//    if ([inData isKindOfClass:[NSData class]] && [inData length]>0) {
//        NSString *fileName = @"";
//        if (inType && [inType isEqualToString:@"image/png"]) {
//            fileName = [NSString stringWithFormat:@"%d.png",[AppUtility getRand]];
//        }else if (inType && [inType isEqualToString:@"image/jpeg"]) {
//            fileName = [NSString stringWithFormat:@"%d.jpg",[AppUtility getRand]];
//        } else if (inType && [inType isEqualToString:@"audio/amr"]) {
//            fileName = [NSString stringWithFormat:@"%d.amr",[AppUtility getRand]];
//        }
//        
//        [asiFormRequest addData:inData withFileName:fileName andContentType:inType forKey:inDataKey];
//    }
    
    
    NSString *fileName = @"";
    fileName = [NSString stringWithFormat:@"%d.jpg",[AppUtility getRand]];
    for (int i = 0; i<imageArray.count; i++) {
        
        [asiFormRequest addData:UIImageJPEGRepresentation([imageArray objectAtIndex:i],0.5) withFileName:fileName andContentType:@"image/jpeg" forKey:[NSString stringWithFormat:@"%@_%d",inDataKey,i]];

    }
    
    [asiFormRequest setTimeOutSeconds:20];
    [asiFormRequest setDelegate:self];
    
    [asiFormRequest buildRequestHeaders];
    [asiFormRequest startSynchronous];
    
    UEXNSLog(@"1111111111-----%@",[asiFormRequest responseString]);
    return [[asiFormRequest responseString] JSONValue];
}


//显示请稍后 上传图片等
+ (id)getDataWithURLStr:(NSString*)inURLString andPostStr:(NSString*)inPostStr andType:(NSString*)inType andData:(NSData*)inData andDataKey:(NSString*)inDataKey {
    
    
	ASIFormDataRequest *asiFormRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:inURLString]];

    
	if ([inPostStr isKindOfClass:[NSString class]] && inPostStr.length != 0) {
		[asiFormRequest setPostValue:inPostStr forKey: @"postData"];
	}
	if ([inData isKindOfClass:[NSData class]] && [inData length]>0) {
		NSString *fileName = @"";
        if (inType && [inType isEqualToString:@"image/png"]) {
			fileName = [NSString stringWithFormat:@"%d.png",[AppUtility getRand]];
		}else if (inType && [inType isEqualToString:@"image/jpeg"]) {
			fileName = [NSString stringWithFormat:@"%d.jpg",[AppUtility getRand]];
		} else if (inType && [inType isEqualToString:@"audio/amr"]) {
			fileName = [NSString stringWithFormat:@"%d.amr",[AppUtility getRand]];
		}

		[asiFormRequest addData:inData withFileName:fileName andContentType:inType forKey:inDataKey];
	}
    
////    NSString *fileName = [[NSBundle mainBundle] pathForResource:@"color_blue" ofType:@"png"];
//    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL: [NSURL URLWithString: inURLString]];
//    //[request setPostValue:@"photo" forKey:@"type"];
//    [request setFile:fileName forKey:@"image"];
//    //    [request buildRequestHeaders];
//    //    [request buildPostBody];
//    [request setDelegate:self];
    [asiFormRequest setTimeOutSeconds:20];
    [asiFormRequest setDelegate:self];

    [asiFormRequest buildRequestHeaders];
    [asiFormRequest startSynchronous];

	return [[asiFormRequest responseString] JSONValue];
}

//用于同步Post
+ (id)getDataWithURLStr:(NSString*)inURLString andPostStr:(NSString*)inPostStr andView:(UIView *)inView {
    
longinOver:
	if (![self isConnected]) {
        
   
        [inView makeToast:@"请检查您的网络或稍后重试"];
		return nil;
	}
    
	[AppUtility showNetworkActivityIndicator:YES];
//    LoadingView *loadView = [[LoadingView alloc]initWithSuperView:inView];
	NSMutableDictionary *hudDict = [self addHudDictInView:inView andStr:@"  请稍候...  "];
	[self displayHudDict:hudDict];
	NetHttp *httpRequest = [[NetHttp alloc] init];
	NSData *data =  [httpRequest sendPostRequestWithURLStr:inURLString andPostStr:inPostStr];

	[httpRequest release];
	if (!data) {
//        [loadView removeFromSuperview];
        [self releaseHudDict:hudDict];

		[AppUtility showNetworkActivityIndicator:NO];
		return nil;
	}
    
//    [loadView removeFromSuperview];
    [self releaseHudDict:hudDict];
	[AppUtility showNetworkActivityIndicator:NO];
    NSDictionary *tmpDict = [JSONParser parserData:data isAllValues:YES valueForKey:nil];
    
    if (tmpDict && [tmpDict isKindOfClass:[NSDictionary class]])
    {
        if ([tmpDict objectForKey:@"s"])
        {

         
            int status =[[tmpDict objectForKey:@"s"] intValue];
                
            if (status==0)
            {
                return tmpDict;
            }
                
               
            if (status==404)
              
            {

                
                NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:KUDAppTDWNO];
                
                NSString *passStr = [[NSUserDefaults standardUserDefaults] objectForKey:KUDAppTDWPass];
                
                if (![name isEqualToString:@""]&&name!=passStr) {
                    
                    NSString *postStr = [NSString stringWithFormat:@"m=%@&p=%@",name, [MD5Digest md5:passStr]];
                    NSDictionary *resultDict =[NetUtility getDataWithURLStr:[NSString stringWithFormat:@"%@%@",KURLLogin,postStr] andPostStr:nil];
                    UEXNSLog(@" -------%@%@  resultDict = %@",KURLLogin,postStr,resultDict);
                    if (resultDict) {
                        int stauts = [[resultDict objectForKey:@"s"] intValue];
                        
                        if (stauts==1) {
                            
                            
                            [AccountController setAccountState:kAccountStateLogin];
                            [AccountController setAccountInfo:[resultDict objectForKey:@"d"]];
                            
                            
                            goto longinOver;

                            
                        }
                    }
                    
                    
                }


                
            }

            

        }
    }
	return tmpDict;
}


//显示请稍后 上传图片等，参数为字典类型
+ (id)getDataWithURLStr:(NSString*)inURLString andPostDict:(NSDictionary*)inPostDict andType:(NSString*)inType andData:(NSData*)inData andDataKey:(NSString*)inDataKey {
	ASIFormDataRequest *asiFormRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:inURLString]];
    
        
	if ([inPostDict isKindOfClass:[NSDictionary class]] && [inPostDict count] != 0) {
        for (NSString *key in [inPostDict allKeys]) {
            [asiFormRequest setPostValue:[inPostDict objectForKey:key] forKey: key];
        }
	}
	if ([inData isKindOfClass:[NSData class]] && [inData length]>0) {
		NSString *fileName = @"";
        if (inType && [inType isEqualToString:@"image/png"]) {
			fileName = [NSString stringWithFormat:@"%d.png",[AppUtility getRand]];
		}else if (inType && [inType isEqualToString:@"image/jpeg"]) {
			fileName = [NSString stringWithFormat:@"%d.jpg",[AppUtility getRand]];
		} else if (inType && [inType isEqualToString:@"audio/amr"]) {
			fileName = [NSString stringWithFormat:@"%d.amr",[AppUtility getRand]];
		}

		[asiFormRequest addData:inData withFileName:fileName andContentType:inType forKey:inDataKey];
	}  
    [asiFormRequest buildRequestHeaders];
    [asiFormRequest startSynchronous];

	return [[asiFormRequest responseString] JSONValue];
}

////用于异步Get
//+ (id)getDataWithURLStr:(NSString*)inURLString andQueryStr:(NSString*)inQueryStr andGetStr:(NSString*)inGetStr {
//	if (![self isConnected]) {
//		UIAlertView* alertView= [[UIAlertView alloc] initWithTitle:@"网络错误"
//														   message:@"请检查您的网络或稍后重试"
//														  delegate:nil
//												 cancelButtonTitle:@"确定"
//												 otherButtonTitles:nil];
//		[alertView show];
//		[alertView release];
//		return nil;
//	}
//	[AppUtility showNetworkActivityIndicator:YES];	
//	NetHttp *httpRequest = [[NetHttp alloc] init];
//	NSData *data =  [httpRequest sendGetRequestWithURLStr:inURLString andQueryStr:inQueryStr andGetStr:inGetStr];
//	[httpRequest release];
//	[AppUtility showNetworkActivityIndicator:NO];
//	if (!data) {
//		return nil;
//	}
//	return [JSONParser parserData:data isAllValues:YES valueForKey:nil];
//}

//用于cache Get
+ (id)getDataWithURLStr:(NSString*)inURLString andQueryStr:(NSString*)inQueryStr andGetStr:(NSString*)inGetStr {
	/*if (![self isConnected]) {
		UIAlertView* alertView= [[UIAlertView alloc] initWithTitle:@"网络错误"
														   message:@"请检查您的网络或稍后重试"
														  delegate:nil
												 cancelButtonTitle:@"确定"
												 otherButtonTitles:nil];
		[alertView show];
		[alertView release];
		return nil;
	}*/
	[AppUtility showNetworkActivityIndicator:YES];
    NSString *urlStr = inURLString;
	if (inQueryStr) {
		urlStr = [NSString stringWithFormat:@"%@?%@",inURLString,inQueryStr];
	}
	UEXNSLog(@"full url is %@", urlStr);
	urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	NSURL *url=[NSURL URLWithString:urlStr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    //设置缓存方式
    //[request setDownloadCache:theApp.mCache];
    //[request setSecondsToCache:60*60*24*30];
    //设置缓存数据存储策略，这里采取的是如果无更新或无法联网就读取缓存数据
    //[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
    //[request didUseCachedResponse];
    [request startSynchronous];
    UEXNSLog(@"request header=%@",[request responseHeaders]);
    request.delegate = self;
    NSData *data =[request responseData];
	[AppUtility showNetworkActivityIndicator:NO];
	if (!data) {
		return nil;
	}
	return [JSONParser parserData:data isAllValues:YES valueForKey:nil];
}

//用于同步Get
+ (id)getDataWithURLStr:(NSString*)inURLString andQueryStr:(NSString*)inQueryStr andGetStr:(NSString*)inGetStr andView:inView {
	if (![self isConnected]) {
		UIAlertView* alertView= [[UIAlertView alloc] initWithTitle:@"网络错误" 
														   message:@"请检查您的网络或稍后重试" 
														  delegate:nil 
												 cancelButtonTitle:@"确定" 
												 otherButtonTitles:nil];
		[alertView show];
		[alertView release];
		return nil;
	}
	[AppUtility showNetworkActivityIndicator:YES];	
	NSMutableDictionary *hudDict = [self addHudDictInView:inView andStr:@"  请稍候...  "];
	[self displayHudDict:hudDict];	
	NetHttp *httpRequest = [[NetHttp alloc] init];
	NSData *data =  [httpRequest sendGetRequestWithURLStr:inURLString andQueryStr:inQueryStr andGetStr:inGetStr];
	[httpRequest release];
	if (!data) {
		[self releaseHudDict:hudDict];
		[AppUtility showNetworkActivityIndicator:NO];
		return nil;
	}
	[self releaseHudDict:hudDict];	
	[AppUtility showNetworkActivityIndicator:NO];
	return [JSONParser parserData:data isAllValues:YES valueForKey:nil];
}

+(UIViewController*)viewController:(UIView *)myView
{
    for (UIView* next = [myView superview]; next; next =
         next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController
                                         class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}


@end
